package boot.spring.service.impl;

import java.util.List;
import java.util.Map;

import org.activiti.engine.IdentityService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageHelper;

import boot.spring.mapper.PurchaseApplyMapper;
import boot.spring.po.PurchaseApply;
import boot.spring.service.PurchaseService;

import javax.annotation.Resource;

@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 5)
@Service
public class PurchaseServiceImpl implements PurchaseService {

    @Resource
    private PurchaseApplyMapper purchaseApplyMapper;
    @Resource
    private IdentityService     identityService;
    @Resource
    private RuntimeService      runtimeService;
    @Resource
    private TaskService         taskService;
    @Resource
    private RepositoryService   repositoryService;

    public ProcessInstance startWorkflow(PurchaseApply apply, String userid, Map<String, Object> variables) {
        purchaseApplyMapper.save(apply);
        String businessKey = String.valueOf(apply.getId());//使用leaveapply表的主键作为businesskey,连接业务数据和流程数据
        identityService.setAuthenticatedUserId(userid);
        ProcessInstance instance = runtimeService.startProcessInstanceByKey("purchase", businessKey, variables);
        String instanceId = instance.getId();
        apply.setProcessinstanceid(instanceId);
        purchaseApplyMapper.updateByPrimaryKeySelective(apply);
        return instance;
    }

    public PurchaseApply getPurchase(int id) {
        return purchaseApplyMapper.getPurchaseApply(id);
    }

    public void updatePurchase(PurchaseApply a) {
        purchaseApplyMapper.updateByPrimaryKeySelective(a);
    }

    @Override
    public List<PurchaseApply> listPurchaseApplyByApplyer(String username) {
        return purchaseApplyMapper.listPurchaseApplyByApplyer(username);
    }

    @Override
    public List<PurchaseApply> listPurchaseApplyByApplyer(String username, int current, int rowCount) {
        PageHelper.startPage(current, rowCount);
        return purchaseApplyMapper.listPurchaseApplyByApplyer(username);
    }

}
